package com.googlecode.shapeline.service.impl;

import com.googlecode.shapeline.core.User;
import com.googlecode.shapeline.service.UserService;
import com.ibatis.sqlmap.client.SqlMapClient;

public class UserServiceImpl implements UserService {
	private static final org.apache.log4j.Logger log = org.apache.log4j.LogManager.getLogger(UserServiceImpl.class);
	private SqlMapClient sqlMapClient;
	
	public SqlMapClient getSqlMapClient() {
		return sqlMapClient;
	}
	
	public void setSqlMapClient(SqlMapClient sqlMapClient) {
		this.sqlMapClient = sqlMapClient;
	}
	
	@Override
	public User login(String name, String password) {
		try {
			//数据库查询用户数据
			User u = (User)getSqlMapClient().queryForObject("selectUser", name);
			if (u == null) {
				log.debug("cannot find user");
				throw new RuntimeException("用户名或密码错误");
			}
			
			//对照密码
			if (!u.getPassword().equals(password)) {
				log.debug("password error");
				throw new RuntimeException("用户名或密码错误");
			}
			
			//检查锁定标志
			if (u.isLocked()) {
				log.debug("user is locked");
				throw new RuntimeException("账户已经锁定");
			}
			
			//通过检查，返回用户
			return u;
		}
		catch (Exception e) {
			throw new RuntimeException("登录时发生异常", e);
		}
	}
}
